package cn.sym.basic.service.impl;

import cn.sym.basic.baseConstant.BaseConstant;
import cn.sym.basic.dto.LoginDto;
import cn.sym.basic.dto.WechatBinderDto;
import cn.sym.basic.exception.MyException;
import cn.sym.basic.jwt.JwtUtils;
import cn.sym.basic.jwt.LoginData;
import cn.sym.basic.jwt.RsaUtils;
import cn.sym.basic.service.ILoginService;
import cn.sym.basic.util.AjaxResult;
import cn.sym.basic.util.HttpClientUtils;
import cn.sym.basic.util.MD5Utils;
import cn.sym.basic.util.StrUtils;
import cn.sym.org.domain.Employee;
import cn.sym.org.mapper.EmployeeMapper;
import cn.sym.system.domain.Menu;
import cn.sym.user.domain.Logininfo;
import cn.sym.user.domain.User;
import cn.sym.user.domain.Wxuser;
import cn.sym.user.mapper.LogininfoMapper;
import cn.sym.user.mapper.UserMapper;
import cn.sym.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    //spring的EL表达式
    @Value("${jwt.rsa.pri}")
    private String priKey;

    /**
     * 账号密码登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        //System.out.println(loginDto);
        //1.空值校验
        if (StringUtils.isEmpty(loginDto.getUsername()) || StringUtils.isEmpty(loginDto.getType()) || StringUtils.isEmpty(loginDto.getPassword())){
            throw new MyException("请输入正确的账号或密码！");
        }
        //2.根据username+type查询数据库看是否已经注册过
        Logininfo logininfo = logininfoMapper.loadByloginDto(loginDto);
        System.out.println(logininfo);
        if (logininfo==null){
            throw new MyException("账号不存在，请注册账号！");
        }
        //3.判断密码是否一致
        String salt = logininfo.getSalt();
        String md5Pwd = MD5Utils.encrypByMd5(loginDto.getPassword() + salt);
        if(!md5Pwd.equals(logininfo.getPassword())){
            throw new MyException("密码不正确！！！");
        }
        //4.是否被禁用
        if(logininfo.getDisable().intValue() == 0){
            throw new MyException("账号被禁用，请联系管理员");
        }
       /* //5.将登录信息存储到redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo, //把根据username+type查询数据库的对象存储到redis    对象需要实现序列化接口public class BaseDomain implements Serializable {}
                30,
                TimeUnit.MINUTES
        );
        //6.返回token + logininfo
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        //返回logininfo对象时把密码和盐值置空返回，安全问题
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/

        //使用jwt代替redis存储登录信息

        return loginSuccessJwtHandler(logininfo);
    }

    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        try {
        LoginData loginData = new LoginData();
        //如果type值为1，说明这个人是前端用户，那么我们不需要去查询他的菜单信息和权限
        if (logininfo.getType().intValue()==1){
            //通过logininfo的id去查询出这个user对象
            User user = userMapper.loadUserByLogininfoId(logininfo.getId());
            user.setSalt(null);
            user.setPassword(null);
            loginData.setUser(user);
        }else{
            //到这个地方就表示这个人不是前端用户，那么就只可能是后端employee  权限信息和菜单信息
            Employee employee = employeeMapper.loadEmployeeByLogininfoId(logininfo.getId());
            employee.setSalt(null);
            employee.setPassword(null);
            loginData.setAdmin(employee);
            List<String> snlist = employeeMapper.loadPerssionSnByLogininfoId(logininfo.getId());
            List<Menu> menus = employeeMapper.loadMenusByLogininfoId(logininfo.getId());
            System.out.println("对应的菜单："+menus);
            loginData.setPermissions(snlist);
            loginData.setMenus(menus);
        }
           //获取到私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(priKey).getFile());
            //使用jwt工具类进行加密
            String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 12*60);
            log.info("你的加密之后的jwt是：{}",jwtStr);
            Map<String,Object> map = new HashMap<>();
            map.put("token",jwtStr);
            if (loginData.getUser()!=null){
                map.put("user",loginData.getUser()); //用户信息
            }else {
                map.put("user",loginData.getAdmin()); //employee信息
            }
            map.put("menus",loginData.getMenus());
            map.put("permissions",loginData.getPermissions());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微信扫码登录
     * @param param
     * @return
     */
    @Override
    public AjaxResult wechat(Map<String, String> param) {
        //1.接收返回的code值
        String code = param.get("code");    //061P5y0008pKkN1Szp000v3Atk0P5y07
        //2.根据code从微信去获取token + openId
        String token_url = BaseConstant.LoginConstant.TOKEN_URL.replace("APPID", BaseConstant.LoginConstant.APPID)
                .replace("SECRET", BaseConstant.LoginConstant.SECRET)
                .replace("CODE", code);
        String tokenStr  = HttpClientUtils.httpGet(token_url);
        JSONObject jsonObject = JSONObject.parseObject(tokenStr);
        System.out.println(jsonObject);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");    //openid -> oa9wA0_luNRswKAE03DPgss9acMM
        //3.根据openId查询本地的t_wxuser，看是否曾今已经扫码过
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);
         //3.1. 有值且t_wxuser表中的user_id有值 曾今已经扫过,本次扫码登录直接免密登录
        if (wxuser!=null && wxuser.getUserId()!=null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            /*String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,   // 要把对象存储到redis 对象需要实现序列化接口
                    30,
                    TimeUnit.MINUTES
            );
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //作为高级技师，应该考虑到将一些敏感字段置空  salt pwd
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo", logininfo);*/
            return AjaxResult.my().setSuccess(true).setResultObj(loginSuccessJwtHandler(logininfo));
        }
         //3.2. 没有，需要走微信绑定流程
         //需要返回：access_token 和 openid
        String binderParams = "?accessToken="+access_token+"&openId="+openid;
        return AjaxResult.my().setSuccess(false).setResultObj(binderParams);
    }

    /**
     * 微信绑定流程
     * @param wechatBinderDto
     * @return
     */
    @Override
    public Map<String, Object> wechatBinder(WechatBinderDto wechatBinderDto) {
        //接收前端参数进行校验
        if (StringUtils.isEmpty(wechatBinderDto.getPhone())){
            throw new MyException("电话号码不能为空！！");
        }
        //获取redis中的短信验证码，如果有表示还没过期，拿不到表示已经过期了
        String smsCodeKey = BaseConstant.SmsConstant.BUSINESS_BINDER_PREFIX+wechatBinderDto.getPhone();
        Object smscode = redisTemplate.opsForValue().get(smsCodeKey);
        if (smscode==null){
            throw new MyException("验证码已失效，请重新获取！！");
        }
        //拿到了就表示验证码还在有效期内，使用原来的验证码
        String smsCode = smscode.toString().split(":")[0];
        //校验输入的验证码与redis中的验证码是否一致,如果不一样，提示用户输入的验证码有误！
        if (!smsCode.equalsIgnoreCase(wechatBinderDto.getSmsCode())){
            throw new MyException("验证码错误，请重新输入！！");
        }
        //判断手机号是否已经注册
        User user = userMapper.loadByPhone(wechatBinderDto.getPhone());
        Logininfo logininfo = null;
        //如果user不为空，表示已经注册过，通过userid去查询logininfo对象
        if (user!=null){
            Wxuser wxuser = wxuserMapper.loadByUserId(user.getId());
            if (wxuser!=null){
                throw new MyException("此用户已绑定微信！！！");
            }
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }else{
            //user为空，表示没有注册过 创建新的t_user t_logininfo
            user = initUser(wechatBinderDto.getPhone());
            logininfo = user2Logininfo(user);
            logininfoMapper.add(logininfo);  //返回自增长的logininfo的id
            //把返回的自增长的id设置进user表的logininfo_id字段
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        //根据accessToken 和 openid查询微信用户信息
        String wxUserUrl = BaseConstant.LoginConstant.WXUSER_URL
                .replace("ACCESS_TOKEN",wechatBinderDto.getAccessToken())
                .replace("OPENID",wechatBinderDto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        // 根据微信返回的信息创建t_wxuser，设置初始值
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        //t_wxuser绑定平台user_id
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        //免密登录
       /* String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,   // 要把对象存储到redis 对象需要实现序列化接口
                30,
                TimeUnit.MINUTES
        );
        //6.返回token + logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //作为高级技师，应该考虑到将一些敏感字段置空  salt pwd
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);*/
        return loginSuccessJwtHandler(logininfo);
    }

    /**
     * 初始化logininfo
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        //一定不要忘记设置type 1表示用户
        logininfo.setType(1);
        logininfo.setDisable(1);
        return logininfo;
    }

    /**
     * 初始化user对象
     * @param phone
     * @return
     */
    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 默认密码是1  发短信告诉他自己去修改
        String md5Pwd = MD5Utils.encrypByMd5("666666" + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return  user;
    }

}
